package ai.mspbots.service.users.filters;

import co.elastic.apm.api.ElasticApm;
import co.elastic.apm.api.Span;
import co.elastic.apm.api.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class HeaderFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(HeaderFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String traceId = ((HttpServletRequest) servletRequest).getHeader("trace.id");
        String transactionId = ((HttpServletRequest) servletRequest).getHeader("transaction.id");
        Transaction transaction = ElasticApm.currentTransaction();
        Span span = transaction.startSpan();
        logger.info("header[trace.id: {},transaction.id:{}],transaction[trace.id: {},transaction.id: {}, span.id: {}]", traceId, transactionId, transaction.getTraceId(), transaction.getId(), span.getId());
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
